<?php

if(!defined("INDEX"))
    die;

$VALID_CATS = array
(
    'todo' => _('Todo'),
    'add_artist' => _('Add artist'),
    'add_release' => _('Add release'),
    'add_watch' => _('Add watch'),
    'add_leak' => _('Add leak'),
    'register' => _('Register'),
    'login' => _('Login'),
    'logout' => _('Logout'),
    'commit_artist' => _('Commit artist'),
    'commit_registration' => _('Commit registration'),
    'commit_release' => _('Commit release'),
    'authorize' => _('Authorize'),
    'view_artist' => _('View artist'),
    'view_release' => _('View release'),
    'home' => _('Home'),
    'watch' => _('Watch releases'),
    'settings' => _('Settings'),
    'unsubscribe' => _('Unsubscribe'),

    'comment_artist' => _('Comment artist'),
    'comment_release' => _('Comment release'),
    'edit_artist' => _('Edit artist'),
    'edit_release' => _('Edit release'),
    'delete_release' => _('Delete release'),
    'delete_artist' => _('Delete artist'),

    'view_all_releases' => _('View releases'),

    'error_404' => _('Error 404'),
    'search' => _('Search'),

    'admin' => _('Administer'),

    'cron' => _('cron')
);

$DEFAULT_CAT = 'home';
$DEFAULT_MODE = 'artists';


function get_cat_title($cat) {

    global $VALID_CATS;

    return $VALID_CATS[$cat];
}
	
function valid_var($var)
{
    if($var == NULL)
	return true;

    return (preg_match('/^[\w\d_]+$/', $var));
}

function valid_cat($cat)
{
	global $VALID_CATS;

	return(in_array($cat, array_keys($VALID_CATS)));
}

function valid_id($id)
{
	return(preg_match('/^(\d)+$/', $id));
}

function valid_name($name)
{
	return(!preg_match('/^[\+\-\)\(\*\&\^\%\$\#\@\!\,\.\']+$/', $name));
}

function valid_page($page)
{
        return(preg_match('/^(\d)*$/', $page));
}

function report_hack_and_exit($ip, $file, $line)
{
    // todo: write to db
    global $main;
    global $start_time;

    $end_time = microtime();
    $end_array = explode(" ", $end_time);
    $end_time = $end_array[1] + $end_array[0];
    $time = round($end_time - $start_time, 2);

    //header('Location: /');
    $main->assign('time', $time);

    $main->newBlock('error');
    $main->assign('msg', _('Thank you for your hack attempts. Your activity is appreciated and will be reported.'));
    $main->assign('img', '/secret/haruhi.jpg');
    $main->assign('alt', _('Haruhi'));
    $main->newBlock('back');
    $main->printToScreen();

    global $CONNS;

    foreach($CONNS as $conn)
        pg_close($conn);

    exit;
}

function get_default_mode_sort($mode)
{
    switch($mode)
    {
	case 'artists':
	    return 'by_artist';
	case 'releases':
	    return 'by_release';
	case 'schedules':
	    return 'by_schedule';
    }
}

function get_album_length($seconds)
{
    if(intval($seconds) == 0)
        return NULL;

    $m = floor($seconds / 60);
    $s = $seconds % 60;
    return $m.':'.$s;
}

function get_seconds($length)
{
    if(preg_match('/^[0-9][0-9]:[0-9][0-9]$/', $length)) {

        list($m, $s) = explode(':',$length,2);

        return $m*60 + $s;
    } else
        return null;
}

function extract_year_from_string($str)
{
    $year = array();
    preg_match('/(\d){4}/', $str, $year);

    if(count($year) == 0)
        return false;
    else
        return $year[0];
}

function extract_cute_date_from_string($str)
{
    $date = array();
    if(preg_match('/(\d){4}\-(\d){2}\-(\d){2}/', $str, $date))
        return $date[0];
    else
    {
        $qpos = strpos($str, '?');

        if($qpos === false)
            return extract_year_from_string($str);
        else
            return substr($str, 0, $qpos-1);
    }
}


function wrapArtistName($str)
{
    $str = htmlentities($str, ENT_QUOTES, 'UTF-8');
    //$str = urlencode($str);
    if(strlen($str) > MAX_ARTIST_CHARS)
        return substr($str, 0, MAX_ARTIST_CHARS) . '...';
    else
        return $str;
}

function wrapReleaseName($str)
{
    $str = htmlentities($str, ENT_QUOTES, 'UTF-8');
    if(strlen($str) > MAX_RELEASE_CHARS)
        return substr($str, 0, MAX_RELEASE_CHARS). '...';
    else
        return $str;
}

function wrapTagName($str)
{
    $str = htmlentities($str, ENT_QUOTES, 'UTF-8');
    if(strlen($str) > MAX_TAG_CHARS)
        return substr($str, 0, MAX_TAG_CHARS) . '...';
    else
        return $str;
}

function wrapArtistLink($str)
{
    $str = urlencode(str_replace(' ', '+', trim($str)));
    $str = str_replace('%26', '%2526', $str);
    return $str;
}

function wrapReleaseLink($str)
{
    $str = urlencode(str_replace(' ', '+', trim($str)));
    $str = str_replace('%26', '%2526', $str);
    return $str;
}

function remoteSize($remoteFile)
{
    $ch = curl_init($remoteFile);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data === false) {
      return false;
    }

    $contentLength = 'unknown';
    $status = 'unknown';
    if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
      $status = (int)$matches[1];
    }
    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
      $contentLength = (int)$matches[1];
    }

    return $contentLength;
}


function check_get() {

    $args = func_get_args();

    foreach($args as $arg)
        if(!isset($_GET[$arg]))
            return false;

    return true;
}

function check_post() {

    $args = func_get_args();

    foreach($args as $arg)
        if(!isset($_POST[$arg]))
            return false;

    return true;
}

function check_request() {

    $args = func_get_args();

    foreach($args as $arg)
        if(!isset($_REQUEST[$arg]))
            return false;

    return true;
}

function is_upcoming_date($value) {

    if(!preg_match('/^[\d]{4}\-[\d]{2}\-[\d]{2}$/', $value))
        return true;

    $data = explode('-', $value);
    if(!checkdate($data[1], $data[2], $data[0]))
        return true;

    if(strtotime($value) > strtotime(date('Y-m-d')))
        return true;

    return false;
}

function firstGenre($str) {

    static $skip_genres = array ('seen live', 'must check', 'sexy voice');

    if(strpos($str, ',') !== false)
        $data = explode(',', $str);
    else
        $data = array($str);

    $res = current($data);

    while(in_array($res, $skip_genres))
        $res = next($data);

    //$res = @current(explode(',', $str, 2));

    return $res;
}

function filterGenre($str, $filter) {

    preg_match("/$filter([^,]*),?/i", $str, $m);
    return $filter.$m[1];
}

function var_dump_pre($var) {
    echo '<pre>';
    var_dump($var);
    echo '</pre>';
}

function obtainHTTPVar($var, $default = NULL) {

    if(isset($_REQUEST[$var]))
        return $_REQUEST[$var];
    else
        return $default;
}

function set_lang($lang) {

    $codeset = "UTF8";
    
    // for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems

    putenv('LANG='.$lang.'.'.$codeset);
    putenv('LANGUAGE='.$lang.'.'.$codeset);
    bind_textdomain_codeset(DOMAIN, $codeset);

    // set locale
    bindtextdomain(DOMAIN, $_SERVER['DOCUMENT_ROOT'].'/locale/');
    setlocale(LC_ALL, $lang.'.'.$codeset);
    textdomain(DOMAIN);
}

function set_lang_auto() {

    $auth = new Auth;

    $lang = $auth->getLangAuto();

    set_lang($lang);
}